﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MetaballParticle : MonoBehaviour, ISubPhysicsCollider
{
    [Header("生成器")]
    private Transform parent;
    public uint id;
    
    private void Awake()
    {
        rigid = GetComponent<Rigidbody2D>();
        collider = GetComponent<CircleCollider2D>();
        sprite = GetComponent<SpriteRenderer>();
        parent = this.transform.parent;
        Active = true;
    }
    private void Update()
    {

      if (Active)
        {
            FluidProcessSubmodule.instance.WaterDataDIC[id].pos = this.transform.position;
            if (scaleDown)
            {
                ScaleDown();
            }

            VelocityLimiter();


        }
    }
    /// <summary>
    /// 处理碰撞信息
    /// </summary>
    /// <param name="collision"></param>
    private void OnCollisionEnter2D(Collision2D collision)
    {
        ISubPhysicsCollider stressed = collision.gameObject.GetComponent<ISubPhysicsCollider>();
        if (stressed == null)
        {
            Debug.LogWarning($"{collision.gameObject.name}上未挂对应接口");
            return;
        }
        var t = stressed.GetCollideInfos(collision);
        foreach (var x in t)
        {
            var args = new CollisionArgs();
            args.StressedID = id;
            args.StressedState = FluidProcessSubmodule.instance.WaterDataDIC[id].elementState;
            args.StressedSystem = BelongingSystem.Fluid;
            args.StressingID = x.Identity.Item1;
            args.StressingState = x.Identity.Item3;
            args.StressingSystem = x.Identity.Item2;
            CollisionForceInfo forceInfo = new CollisionForceInfo();
            forceInfo.WorldPos = x.CollidePositionInWorld;
            forceInfo.Force = x.Force;
            args.Info = forceInfo;
            parent.GetComponent<WaterFather>().colliderInfos.Add(args);
        }
    }
   /* public Tuple<int,string> GetSystem(Collider2D collider)
    {
        int id=collider.gameObject.GetComponent<MetaballParticle>().baseInfo.idEntity;
        return new Tuple<int,string>(id,"流体");
    }*/

    void ScaleDown()
    {
        if (!ScaleDownIsPerforming)
        {
            ScaleDownIsPerforming = true;
        }

        if (ScaleDownIsPerforming)
            transform.localScale = Vector2.Lerp(transform.localScale, new Vector2(endSize, endSize), (delta / lifetime) * Time.deltaTime * .8f);
    }
    void VelocityLimiter()
    {
        if (Editor_Velocity.x > Velocity_Limiter_X)
        {
            Editor_Velocity.x = Velocity_Limiter_X;
        }
        if (Editor_Velocity.y > Velocity_Limiter_Y)
        {
            Editor_Velocity.y = Velocity_Limiter_Y;
        }
    }
    /// <summary>
    /// 根物体
    /// </summary>
    [Header("根物体")]
    public GameObject root;
    /// <summary>
    /// 生命周期
    /// </summary>
    [Header("生命周期")]
    public float lifetime;
    /// <summary>
    /// 是否大小随生命周期衰减
    /// </summary>
    [Header("大小是否随生命周期衰减")]
    public bool scaleDown;
    /// <summary>
    /// 生命结束时的大小
    /// </summary>
    [Header("衰减最后的大小")]
    public float endSize = 0f;
    /// <summary>
    ///当前活性
    /// </summary>
    private bool _active;
    /// <summary>
    /// gameobject活性
    /// </summary>
    public bool Active
    {
        get { return _active; }
        set
        {
            _active = value;
            if (root)
            {
                root.SetActive(value);

                /*    if (tr)
                        tr.Clear();*/

            }

            if (value)
            {
                delta = 0;
                wakeUpTime = Time.time;

                /*  if (glowSP)
                      glowSP.enabled = true;*/
            }

            if (!value)
            {
                //substrac 1 unit of particle using.

                if (rigid != null) // reset speed simulation in Editor
                    rigid.velocity *= 0f;

                if (_isFreeze)
                {
                    rigid.constraints = RigidbodyConstraints2D.None;
                    rigid.sharedMaterial = null;
                    _isFreeze = false;
                }


                delta = 0;

            }
            ScaleDownIsPerforming = false;

        }
    }
    //  public bool witinTarget;
    /// <summary>
    /// editor速度
    /// </summary>
    [Header("水珠速度")]
    public Vector2 Editor_Velocity; // velocity used within editor simulation
    /// <summary>
    /// x速度
    /// </summary>
    [Header("x最大速度")]
    public float Velocity_Limiter_X; // Limiter of speed in X in simulation
    /// <summary>
                                     /// y速度
                                     /// </summary>
    [Header("y最小速度")]
    public float Velocity_Limiter_Y; // Limiter of speed in X in simulation
    private float delta;
    private float wakeUpTime;
    /// <summary>
    /// 刚体
    /// </summary>
    Rigidbody2D rigid;
    /// <summary>
    /// 碰撞体
    /// </summary>
    CircleCollider2D collider;
    //   TrailRenderer tr;
    /// <summary>
    /// 贴图
    /// </summary>
    SpriteRenderer sprite;
    /// <summary>
    /// 碰撞体组
    /// </summary>
    Collider2D[] Contacts;
    /// <summary>
    /// 当前是否锁轴
    /// </summary>
    bool _isFreeze;
    public bool GetFreeze() => _isFreeze;
    Tuple<uint, BelongingSystem, ElementState> ISubPhysicsCollider.GetObjectInfo()
    {
        return new Tuple<uint, BelongingSystem, ElementState>(id, BelongingSystem.Fluid, FluidProcessSubmodule.instance.WaterDataDIC[id].elementState);
    }

    List<CollideInfo> ISubPhysicsCollider.GetCollideInfos(Collision2D obj)
    {
        Vector2 WorldPos = obj.GetContactPos();
        Vector2 Force =obj.GetForce();
        Tuple<uint,BelongingSystem,ElementState> tuple= new Tuple<uint, BelongingSystem, ElementState>(id, BelongingSystem.Fluid, FluidProcessSubmodule.instance.WaterDataDIC[id].elementState);
        List<CollideInfo> t = new List<CollideInfo>();
        t.Add(new CollideInfo(tuple, WorldPos, Force));
        return t;
    }

    /// <summary>
    /// 当前是否衰减大小；
    /// </summary>
    bool ScaleDownIsPerforming = false;

}
/// <summary>
/// 水珠的基本信息
/// </summary>


